//
//  JCComposeViewController.swift
//  SinaWeibo_18
//
//  Created by apple on 15/10/26.
//  Copyright © 2015年 cz. All rights reserved.
//

//        IWComposeViewController.swift[47], keyboardWillChangeFrame: NSConcreteNotification 0x7f9093137af0 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
//            UIKeyboardAnimationCurveUserInfoKey = 7;
//            UIKeyboardAnimationDurationUserInfoKey = "0.25";
//            UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
//            UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
//            UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
//            UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
//            UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
//            UIKeyboardIsLocalUserInfoKey = 1;
//            }}


import UIKit
//配图view左右间距
private let COMPOSE_PHOTOSVIEW_MARGIN: CGFloat = 10

class JCComposeViewController: UIViewController, UITextViewDelegate, JCComposeToolBarDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        
        
        setupNav()
        
        setupView()
    }
    
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem.item( title: "取消", target: self, action: "cancel")
        
        navigationItem.titleView = titleView
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        
    }
        //添加textview
    private func setupView(){
        //添加textview
        textView.size = CGSizeMake(ScreenWidth, ScreenHeight)
        view.addSubview(textView)
        
        //添加配图的控件
        composePictureView.x = COMPOSE_PHOTOSVIEW_MARGIN
        composePictureView.y = 160
        view.addSubview(composePictureView)
        
        //设置添加按钮的点击逻辑
        composePictureView.addButtonClickBlock = {
           [weak self] () -> () in
            self?.selectPicture()
        }
        
        //添加toolbar
        toolBar.y = ScreenHeight - toolBar.height
        view.addSubview(toolBar)
        
        //监听键盘弹出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //  MARK: - 私有方法
    
    //modal掉控制器
    @objc private func cancel(){
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //选择照片
    private func selectPicture(){
        //初始化图片选择控制器
        let controller = UIImagePickerController()
        //设置图片来源
        controller.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        //设置代理,取到图片
        controller.delegate = self
        //弹出控制器
        self .presentViewController(controller, animated: true, completion: nil)
    }
    //选择键盘
    private func switchKeyboard(){
        //移除第一响应者 切换键盘
        textView.resignFirstResponder()
        
            //设置键盘
       // nil 代表是系统键盘
      textView.inputView = textView.inputView == nil ? keyboard : nil
        
        
        //成为第一响应者(弹出键盘)
        textView.becomeFirstResponder()
        
    }
    
    @objc private func keyboardWillChangeFrame(notifi: NSNotification){
        
//        printLog(notifi)
        //键盘弹出最终位置
        let rect = (notifi.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //键盘弹出动画时间
        let time = (notifi.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //设置toolbar的y值
        UIView.animateWithDuration(time) { () -> Void in
            self.toolBar.y = rect.origin.y - self.toolBar.height
        }
    }
    
    //  MARK: - textViewDelegate
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
    
    //  MARK: - imagePickerController delegate
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //讲选择的图片添加到相册的控件中
        composePictureView.addImage(image.scale(width: 300))
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    //点击取消
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)

    }
    
    //  MARK: - composeToolBar delegate
    func composeToolBar(toolBar: JCComposeToolBar, buttonClickType: JCComposeToolBarButtonType) {
        switch buttonClickType {
        case .picture:
//            printLog("图片")
            selectPicture()
            
        case .Mention:
            printLog("@")
        case .Trend:
            printLog("话题")
        case .Emotion:
            printLog("切换表情键盘")
            switchKeyboard()
            
        case .Add:
            printLog("加号")
        }
    }
    //  MARK: - 懒加载控件
    
    //导航栏标题
    private lazy var titleView: UILabel = {
        let label = UILabel()
        //换行居中
        label.numberOfLines = 0
        label.textAlignment = NSTextAlignment.Center
        if let nicName = JCUserAccount.loadUserAccount()?.screen_name{
            //有昵称
            let title = "发微博\n\(nicName)"
            //去到昵称所在文字范围
            let range = (title as NSString).rangeOfString(nicName)
            //初始化 可变的带有属性文字
            var attr = NSMutableAttributedString(string: title)
            //指定range范围内文字的属性(颜色和字体)
            attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: range)
            attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            //设置带有属性的文字
            label.attributedText = attr
        }else{
            label.text = "发微博"
        }
        label.sizeToFit()
        
        return label
    }()
    
    //导航栏右边item
    private lazy var rightButton: UIButton = {
            let button = UIButton()
        //设置title
        button.setTitle("发送", forState: UIControlState.Normal)
        
        //文字颜色
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        
        //设置不同状态下背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        //设置按钮大小
        button.size = CGSizeMake(44, 30)
        //文字大小
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        return button
        }()
    
    //文字输入框
    private lazy var textView: UITextView = {
            let textView = JCTextView()
            //设置代理
        textView.delegate = self
        //垂直方向的弹簧效果
        textView.alwaysBounceVertical = true
            textView.font = UIFont.systemFontOfSize(16)
            textView.placeholderText = "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"
        
            return textView
        }()
    
    //底部的toolbar
    private lazy var toolBar: JCComposeToolBar = {
            let toolBar = JCComposeToolBar()
        toolBar.delegate = self
        toolBar.size = CGSizeMake(ScreenWidth, 44)
        return toolBar
        }()
    
    //配图的view
    private lazy var composePictureView: JCComposePhotosView = {
        let photosView = JCComposePhotosView()
        //设置大小
        let photosWH = ScreenWidth - COMPOSE_PHOTOSVIEW_MARGIN*2
        photosView.size = CGSizeMake(photosWH, photosWH)
        
        return photosView
    }()

    //表情键盘
    private lazy var keyboard: JCEmotionKeyboard = {
        let keyboard = JCEmotionKeyboard()
        keyboard.size = CGSizeMake(ScreenWidth, 216)
        return  keyboard
        
        }()
}
